package cn.iune.erp.autoentry;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;


@Transactional
@Service
public class EntrySettingServiceImpl implements IEntrySettingService {

	@Autowired
	private IEntrySettingDao dao;
	
	
	@Transactional
	@Override
	public void insert(EntrySetting fc) {
		dao.insert(fc);
	}
	
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}
	
	@Override
	public EntrySetting update(EntrySetting fc) {
		return dao.update(fc);
	}

	@Override
	public EntrySetting getByID(String fID) {
		return dao.getByID(fID);
	}
	
	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		Table table= Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
				
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			EntrySetting obj = JSON.toJavaObject(javaObject, EntrySetting.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				EntrySetting objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("rows", rows);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}




	@Override
	public List<EntrySetting> getByMasterID(String fMasterID) {
		return dao.getByMasterID(fMasterID);
	}
	
	@Override
	public EntrySetting getByNo(String billType, String enterpriseNo) {
		return dao.getByNo(billType, enterpriseNo);
	}

	/*
	public JSONObject query(JSONObject data) throws Throwable {
		
		// 获取参数
		Object columns = data.getJSONObject("columns"); // 列定义
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
		String fMasterID = data.getString("fMasterID");

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("systemCode LIKE ? OR systemName LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 2; i++) {
				sqlParams.add(search);
			}
		}
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
		//处理fMasterID
		if (Utils.isNotEmptyString(fMasterID)) {
			filters.add("fMasterID='"+fMasterID+"'");
		}
	
		
		Table table = Transform.createTableByColumnsDefine((JSONObject) columns);
		
		if (offset != null && offset.equals(0)) {
			long rowCount = dao.getCount(filters, sqlParams);
			table.setTotal((int)rowCount);
		}

		String orderBy = "";
				
		//获取数据
		List<Row> rows = listToRows(dao.query(filters,orderBy,sqlParams,offset,limit));
	    table.appendRows(rows);
		JSONObject json = Transform.tableToJson(table);
	
		return json;
	}


	public int save(JSONObject object) throws Throwable {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		List<EntrySetting> list = rowsToList(table.getRows());
		for(EntrySetting o : list){
			if(RowState.NEW.equals(o.getRowState())){
				dao.insert(o);
			}
			if(RowState.EDIT.equals(o.getRowState())){
				dao.update(o);
			}
			if(RowState.DELETE.equals(o.getRowState())){
				dao.delete(o.getfID());
			}
		}
		return 0;
	}


	public List<Row> listToRows(List<EntrySetting> list){
		//添加行集
		List<Row> rows = new ArrayList<Row>();
		//循环行
	    for(EntrySetting o : list){
	    	rows.add(objectToRow(o));
	    }
	    return rows;
	}

	public List<EntrySetting> rowsToList(List<Row> rows){
		//添加行集
		List<EntrySetting> list = new ArrayList<EntrySetting>();
		//循环行
	    for(Row r : rows){
	    	list.add(rowToObject(r));
	    }
	    return list;
	}

	public Row objectToRow(EntrySetting obj){
    	
		Map<String, ColumnValue> values = new HashMap<String, ColumnValue>();
		//循环行中每一列
		ColumnValue value = new ColumnValue(obj.getfID());
		values.put("fID", value);
		value = new ColumnValue(obj.getfMasterID());
 		values.put("fMasterID", value);
		value = new ColumnValue(obj.getBillType());
 		values.put("billType", value);
		value = new ColumnValue(obj.getBillTypeName());
 		values.put("billTypeName", value);
//		value = new ColumnValue(obj.getSystemCode());
// 		values.put("systemCode", value);
//		value = new ColumnValue(obj.getSystemName());
// 		values.put("systemName", value);
		value = new ColumnValue(obj.getPreChar());
 		values.put("preChar", value);
		value = new ColumnValue(obj.getCodeCount());
 		values.put("codeCount", value);
		value = new ColumnValue(obj.getCodeType());
 		values.put("codeType", value);
		value = new ColumnValue(obj.getCodeTypeLabel());
 		values.put("codeTypeLabel", value);
		value = new ColumnValue(obj.getAutoCode());
 		values.put("autoCode", value);
		value = new ColumnValue(obj.getAutoCodeLabel());
 		values.put("autoCodeLabel", value);
		value = new ColumnValue(obj.getCostingCode());
 		values.put("costingCode", value);
		value = new ColumnValue(obj.getCostingCodeLabel());
 		values.put("costingCodeLabel", value);
		value = new ColumnValue(obj.getRevOpay());
 		values.put("revOpay", value);
		value = new ColumnValue(obj.getRevOpayLabel());
 		values.put("revOpayLabel", value);
		value = new ColumnValue(obj.getDirection());
 		values.put("direction", value);
		value = new ColumnValue(obj.getDirectionLabel());
 		values.put("directionLabel", value);
		value = new ColumnValue(obj.getOrigin());
 		values.put("origin", value);
		value = new ColumnValue(obj.getOriginName());
 		values.put("originName", value);
		value = new ColumnValue(obj.getFlowType());
 		values.put("flowType", value);
		value = new ColumnValue(obj.getFlowTypeLabel());
 		values.put("flowTypeLabel", value);
		value = new ColumnValue(obj.getWindowUrl());
 		values.put("windowUrl", value);
		value = new ColumnValue(obj.getWindowProcess());
 		values.put("windowProcess", value);
		value = new ColumnValue(obj.getWindowActivity());
 		values.put("windowActivity", value);
 		
		value = new ColumnValue(obj.getEnterpriseNo());
 		values.put("enterpriseNo", value);
		value = new ColumnValue(obj.getEnterpriseName());
 		values.put("enterpriseName", value);

 		value = new ColumnValue(obj.getVersion());
 		values.put("version", value);
		
		Row row = new Row(values,RowState.NONE);
		return row;
	}
	
	public EntrySetting rowToObject(Row row){
		EntrySetting obj = new EntrySetting();
		obj.setfID(row.getString("fID"));
		obj.setfMasterID(row.getString("fMasterID"));
		obj.setBillType(row.getString("billType"));
		obj.setBillTypeName(row.getString("billTypeName"));
		obj.setPreChar(row.getString("preChar"));
		obj.setCodeCount(row.getInteger("codeCount"));
		obj.setCodeType(row.getString("codeType"));
		obj.setCodeTypeLabel(row.getString("codeTypeLabel"));
		obj.setAutoCode(row.getString("autoCode"));
		obj.setAutoCodeLabel(row.getString("autoCodeLabel"));
		obj.setCostingCode(row.getString("costingCode"));
		obj.setCostingCodeLabel(row.getString("costingCodeLabel"));
		obj.setRevOpay(row.getString("revOpay"));
		obj.setRevOpayLabel(row.getString("revOpayLabel"));
	    obj.setDirection(row.getInteger("direction"));
	    obj.setDirectionLabel(row.getString("directionLabel"));
	    obj.setOrigin(row.getString("origin"));
	    obj.setOriginName(row.getString("originName"));
	    obj.setFlowType(row.getInteger("flowType"));
	    obj.setFlowTypeLabel(row.getString("flowTypeLabel"));
	    obj.setWindowUrl(row.getString("windowUrl"));
	    obj.setWindowProcess(row.getString("windowProcess"));
	    obj.setWindowActivity(row.getString("windowActivity"));
	    
		obj.setEnterpriseNo(row.getString("enterpriseNo"));
		obj.setEnterpriseName(row.getString("enterpriseName"));

		obj.setVersion(row.getInteger("version"));
		
		obj.setRowState(row.getState());

		return obj;
	}
	*/
	
	@Transactional
	@Override
	public int deleteAll(EntityManager entityManager){
		List<EntrySetting> billSettingList = dao.getAll();
		for(EntrySetting billSetting : billSettingList){
			dao.delete(billSetting.getfID());
		}
		return 0;
	}

	@Override
	public JSONObject newData(JSONObject data) {
		return dao.create(data);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		//System.out.println("fileFactoryCreate.param-->>"+param.toJSONString());
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}

	/*
	在@Transaction注解中定义noRollbackFor和RollbackFor指定某种异常是否回滚。 
	@Transactional(noRollbackFor=RuntimeException.class) 
	@Transactional(RollbackFor=Exception.class) 
	*/
	@Transactional
	@Override
	public JSONObject saveData(JSONObject param) {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		JSONObject data;
		try {
			data = this.save(param);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#queryJDBC(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public JSONObject queryData(JSONObject param){
		//在此层面（ServiceImpl）统一处理异常，此层面直接被controller调用，面对BizData
		
		try {
			JSONObject jsonTable = dao.query(param);
			//System.out.println(this.getClass().getName()+".queryData-->>"+jsonTable);
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}

	@Override
	public JSONObject validData(JSONObject param) {


		JSONObject data = new JSONObject();
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);

		return json;
	}		
}
